<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>+
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>新增商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-alert title="添加商品信息" type="info" center show-icon> </el-alert>
      <el-steps
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          v-model="activeIndex"
          tab-position="left"
          :before-leave="beforeTableave"
          @tab-click="handleTabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                clearable
                :props="{
                  expandTrigger: 'hover',
                  label: 'cat_name',
                  value: 'cat_id'
                }"
                @change="handleCascaderChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 第一层循环 -->
            <el-form-item
              :label="item.attr_name"
              v-for="(item, index) in manyTableData"
              :key="index"
            >
              <el-checkbox-group v-model="item.attr_vals" size="small">
                <!-- 第二层循环 -->
                <el-checkbox
                  :label="subItem"
                  border
                  v-for="(subItem, subIndex) in item.attr_vals"
                  :key="subIndex"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="(item, index) in onlyTableData"
              :key="index"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headers"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 绑定数据到富文本 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" style="margin-top:10px" @click="onSubmit"
              >提交</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog title="预览" :visible.sync="previewDialogVisible" width="50%">
      <img :src="previewUrl" alt="" style="width:100%" />
    </el-dialog>
  </div>
</template>

<script>
import { cloneDeep } from 'lodash'
export default {
  data () {
    return {
      activeIndex: 0,
      addForm: {
        goods_introduce: '', // 商品介绍
        goods_name: '', // 商品名称
        goods_price: 0, // 价格
        goods_number: 0, // 数量
        goods_weight: 0, // 重量
        goods_cat: [], // 分类
        pics: [],
        attrs: []
        // selectedKeys: [],
      },
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ], // 商品名称
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ], // 价格
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ], // 数量
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ], // 重量
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ] // 分类
      },
      cateList: [],
      manyTableData: [],
      onlyTableData: [],
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      headers: {
        Authorization: window.sessionStorage.getItem('token')
      },
      previewUrl: '', // 预览图片路径
      previewDialogVisible: false // 对话框显示变量
    }
  },
  computed: {
    cateId () {
      return this.addForm.goods_cat[this.addForm.goods_cat.length - 1]
    }
  },
  created () {
    this.getCateList()
    // todo:测试语句-start
    this.addForm.goods_cat = [1, 3, 6] // 选中分类
    this.activeIndex = '3' // 切换页签
    this.handleTabClick() // 模拟点击
  },
  methods: {
    onSubmit () {
      this.$refs.addFormRef.validate(async (isOk, error) => {
        if (isOk) {
          console.log('验证成功')
          const formData = cloneDeep(this.addForm)
          formData.goods_cat = this.addForm.goods_cat.join(',')
          this.manyTableData.forEach(t => {
            this.addForm.attrs.push({
              attr_id: t.attr_id,
              attr_value: t.attr_vals.join(' ')
            })
          })
          this.onlyTableData.forEach(t => {
            this.addForm.attrs.push({
              attr_id: t.attr_id,
              attr_value: t.attr_vals
            })
          })
          formData.attrs = this.addForm.attrs
          console.log('formData', formData)
          const { data: res } = await this.$http.post('goods', formData)
          if (res.meta.status !== 201) {
            this.$message({
              message: '新增失败',
              type: 'error',
              showClose: true,
              duration: 3000
            })
          } else {
            this.$message({
              message: '新增成功',
              type: 'success',
              showClose: true,
              duration: 3000
            })
            this.$router.push('/goods')
          }
        } else {
          console.log(error)
          this.$message({
            message: '验证失败',
            type: 'error',
            showClose: true,
            duration: 3000
          })
        }
      })
    },
    handleSuccess (response, file, fileList) {
      console.log(response)
      this.addForm.pics.push({
        pic: response.data.tmp_path
      })
    },
    // 预览方法
    handlePreview (file) {
      console.log(file)
      this.previewUrl = file.response.data.url
      this.previewDialogVisible = true
    },
    handleRemove (file, fileList) {
      console.log(file)
      const tmpPath = file.response.data.tmp_path
      this.addForm.pics = this.addForm.pics.filter(t => t.pic !== tmpPath)
    },
    beforeTableave (activeName, oldActiveName) {
      // if (activeName === '1' && oldActiveName === '0') {
      //   if (this.addForm.goods_cat.length !== 3) {
      //     return false
      //   }
      // }
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        return false
      }
    },
    async handleTabClick () {
      // 商品参数
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: 'many'
            }
          }
        )
        res.data.forEach(t => {
          t.attr_vals = t.attr_vals.length === 0 ? [] : t.attr_vals.split(' ')
        })
        this.manyTableData = res.data
      } else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: 'only'
            }
          }
        )
        this.onlyTableData = res.data
      }
    },
    handleCascaderChange () {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    async getCateList () {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 3 }
      })
      this.cateList = res.data
    }
  }
}
</script>

<style lang="less" scoped></style>
